from fastapi import FastAPI, Form, Request
from fastapi.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
import uvicorn
import models

# 创建app对象
app = FastAPI()
# 创建模板
templates = Jinja2Templates(directory="templates")
# 挂载static目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 初始化数据库
models.init_db()

# 用户列表路由函数
@app.get("/user_list")
async def user_list(request: Request):
    # 1、创建数据库返回用户列表
    userlist = models.find_all()
    # 2、页面跳转
    rsp = templates.TemplateResponse(
        "userlist.html", {"request": request, "userlist": userlist}
    )
    return rsp


# 进入添加用户页面路由函数
@app.get("/adduser")
async def adduser_page(request: Request):
    # 页面跳转
    rsp = templates.TemplateResponse("adduser.html", {"request": request})
    return rsp


# 进入修改用户页面路由函数
@app.get("/updateuser/{userid}")
async def updateuser_page(userid, request: Request):
    # 按照主键擦查询
    drow = models.find_by_id(userid)

    # 页面跳转
    rsp = templates.TemplateResponse(
        "updateuser.html",
        {
            "request": request,
            "userid": drow["userid"],
            "username": drow["username"],
            "email": drow["email"],
            "phone": drow["phone"],
        },
    )
    return rsp


# 进入添加用户到数据库
@app.post("/add_user")
async def adduser_toDB(
    request: Request,
    username: str = Form(default=None),
    userid: str = Form(...),
    email: str = Form(default=None),
    phone: str = Form(default=None),
):
    # 准备数据
    user = {}
    user["user_id"] = userid
    user["email"] = email
    user["phone"] = phone
    user["username"] = username

    # 调用数据层插入数据
    afcount = models.create(user)
    # 页面跳转
    rsp = templates.TemplateResponse(
        "success.html", {"request": request, "result": afcount}
    )
    return rsp


# 进入修改用户到数据库
@app.post("/update_user")
async def upduser_toDB(
    request: Request,
    username: str = Form(default=None),
    userid: str = Form(...),
    email: str = Form(default=None),
    phone: str = Form(default=None),
):
    # 准备数据
    user = {}
    user["user_id"] = userid
    user["email"] = email
    user["phone"] = phone
    user["username"] = username

    # 调用数据层修改数据
    afcount = models.modify(user)
    # 页面跳转
    rsp = templates.TemplateResponse(
        "success.html", {"request": request, "result": afcount}
    )
    return rsp



# 进入删除用户页面路由函数
@app.get("/deleteuser/{userid}")
async def deleteuser_page(userid, request: Request):
    # 删除数据
    models.remove(userid)

    # 重新查询
    userlist = models.find_all()
    # 页面跳转
    rsp = templates.TemplateResponse(
        "userlist.html", {"request": request, "userlist": userlist}
    )
    return rsp


if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
